<script name="CartSku" setup lang="ts">
	import { ApiRes } from '@/types/data'
	import { GoodsInfo, Sku } from '@/types/goods'
	import GoodsSku from '@/views/goods/components/goods-sku.vue'
	import { onClickOutside } from '@vueuse/core'
	import { onMounted, ref } from 'vue'
	import request from '@/utils/request'
	import Message from '@/components/message'

	const props = defineProps({
		attrsText: String,
		skuId: {
			type: String,
			default: '',
		},
	})
	const emit = defineEmits<{
		(e: 'change', sku: Sku): void
	}>()
	// 定义一个控制面板显示与隐藏的属性
	const active = ref(false)
	const toggle = () => {
		active.value = !active.value
	}
	const target = ref<HTMLDivElement | null>(null)
	// 给元素设置一个点击之外的结构关闭面板的事件
	onClickOutside(target, () => {
		active.value = false
	})
	// 定义一个根据 skuid 得到商品对应的所有规格信息的方法
	const goods = ref<GoodsInfo>({} as GoodsInfo)
	onMounted(async () => {
		const res = await request.get<ApiRes<GoodsInfo>>(`/goods/sku/${props.skuId}`)
		goods.value = res.data.result
	})

	let currentSkuId = ''
	const changeSku = (skuId: string) => {
		currentSkuId = skuId
	}

	const submit = () => {
		// 判断currentSkuId有值并且和原来的skuId不能相等
		if (currentSkuId && currentSkuId !== props.skuId) {
			const sku = goods.value.skus.find((item) => item.id === currentSkuId)
			emit('change', sku as Sku)
		} else {
			Message.warning('商品规格不完整或无变化')
		}
	}
</script>

<template>
	<div class="cart-sku" ref="target">
		<div class="attrs" @click="toggle">
			<span class="ellipsis">{{ attrsText }}</span>
			<i class="iconfont icon-angle-down"></i>
		</div>
		<div class="layer" v-if="active">
			<GoodsSku :skuId="skuId" :goods="goods" @changeSku="changeSku"></GoodsSku>
			<XtxButton type="primary" size="mini" style="margin-left: 60px" @click="submit"
				>确认</XtxButton
			>
		</div>
	</div>
</template>

<style scoped lang="less">
	.cart-sku {
		height: 28px;
		border: 1px solid #f5f5f5;
		padding: 0 6px;
		position: relative;
		margin-top: 10px;
		display: inline-block;
		.attrs {
			line-height: 24px;
			display: flex;
			span {
				max-width: 230px;
				font-size: 14px;
				color: #999;
			}
			i {
				margin-left: 5px;
				font-size: 14px;
			}
		}
		.layer {
			position: absolute;
			left: -1px;
			top: 40px;
			z-index: 10;
			width: 400px;
			border: 1px solid @xtxColor;
			box-shadow: 2px 2px 4px lighten(@xtxColor, 50%);
			background: #fff;
			border-radius: 4px;
			font-size: 14px;
			padding: 20px;
			&::before {
				content: '';
				width: 12px;
				height: 12px;
				border-left: 1px solid @xtxColor;
				border-top: 1px solid @xtxColor;
				position: absolute;
				left: 12px;
				top: -8px;
				background: #fff;
				transform: scale(0.8, 1) rotate(45deg);
			}
		}
	}
</style>
